//
//  LFTMCHttpManager.m
//  lofter-mvpcourse-ios
//
//  Created by zmm on 8/5/2017.
//  Copyright © 2017 undefined-zola. All rights reserved.
//

#import "LFTMCHttpManager.h"

#define TestHost   @"59.111.29.38 api.lofter.com"
#define NomalHost  @"api.lofter.com"

@interface LFTMCHttpRequestSerializer : AFHTTPRequestSerializer

@property (nonatomic, copy) NSArray *HTTPParametersInURI;

@end

@implementation LFTMCHttpRequestSerializer

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                 URLString:(NSString *)URLString
                                parameters:(id)parameters
                                     error:(NSError * __autoreleasing *)error
{
    NSMutableURLRequest *mutableRequest = [super requestWithMethod:method URLString:URLString parameters:parameters error:error];
    if (self.HTTPParametersInURI){
        NSString *additionQuery = [self.HTTPParametersInURI componentsJoinedByString:@"&"];
        mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", additionQuery]];
    }
    return mutableRequest;
}
@end

#pragma mark - LFTMCHttpManager -------------

@implementation LFTMCHttpManager

+ (LFTMCHttpManager *)manager
{
    static dispatch_once_t onceToken;
    static LFTMCHttpManager *sharedInstance = nil;
    
    dispatch_once(&onceToken, ^{
        
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://59.111.29.38/v1.1"] sessionConfiguration:sessionConfiguration];
//        sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://10.241.1.8/v1.1"] sessionConfiguration:sessionConfiguration];
        
        LFTMCHttpRequestSerializer *requestSerializer = [LFTMCHttpRequestSerializer serializer];
        [requestSerializer setValue:TestHost  forHTTPHeaderField:@"Host"];

        requestSerializer.HTTPParametersInURI = @[[NSString stringWithFormat:@"product=%@", @"lofter-iphone-5.7.0"]];
        sharedInstance.requestSerializer = requestSerializer;
        [sharedInstance.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        NSMutableSet *newSet = [NSMutableSet set];
        newSet.set = sharedInstance.responseSerializer.acceptableContentTypes;
        [newSet addObject:@"text/html"];
        
        sharedInstance.responseSerializer.acceptableContentTypes = newSet;
        
    });
    
    return sharedInstance;
}

-(void)bindAuth:(NSString *)ursToken mobId:(NSString *)mobId
{
    [self clearAuth];
    [self.requestSerializer setValue:ursToken forHTTPHeaderField:@"URSMobToken"];
    [self.requestSerializer setValue:mobId forHTTPHeaderField:@"URSMobID"];
}

-(void)clearAuth
{
    NSMutableDictionary *authHeader = [self.session.configuration.HTTPAdditionalHeaders mutableCopy];
    [authHeader removeObjectForKey:@"URSMobToken"];
    [authHeader removeObjectForKey:@"URSMobID"];
    self.session.configuration.HTTPAdditionalHeaders = authHeader;
    
    [self.requestSerializer setValue:nil forHTTPHeaderField:@"URSMobToken"];
    [self.requestSerializer setValue:nil forHTTPHeaderField:@"URSMobID"];
}

- (void)fetchTeamInfo:(NSString *)teamId
          lofterToken:(NSString *)token
          lofterMobId:(NSString *)mobId
              success:(void(^)(NSDictionary *))success
              failure:(void (^)(NSError *error))failure
{
    [self bindAuth:token mobId:mobId];
    [self
     POST:@"cloudmsg.api"
     parameters:@{@"method":@"checkUser", @"tId":teamId}
     success:^(NSURLSessionDataTask *task, id responseObject) {
         if (success) {
             success(responseObject[@"response"]);
         }
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         if (failure) {
             failure(error);
         }
     }];
}

- (void)updateTeamMute:(NSString *)teamId
                  mute:(BOOL)isMute
               success:(void(^)())success
               failure:(void (^)(NSError *error))failure
{
    [self
     POST:@"cloudmsg.api"
     parameters:@{@"method":@"muteTlistAll", @"tId":teamId, @"mute":isMute?@"1":@"-1"}
     success:^(NSURLSessionDataTask *task, id responseObject) {
         if (success) {
             success();
         }
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         if (failure) {
             failure(error);
         }
     }];
}

- (void)closeTeamOperation:(NSString *)teamId
                   success:(void(^)())success
                   failure:(void (^)(NSError *error))failure
{
    [self
     POST:@"cloudmsg.api"
     parameters:@{@"method":@"closeTeam", @"tId":teamId}
     success:^(NSURLSessionDataTask *task, id responseObject) {
         if (success) {
             success();
         }
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         if (failure) {
             failure(error);
         }
     }];

}


@end
